package org.brownflat.lighthouse.monitoring.ci;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Feed {
    private List<Build> items = new ArrayList<Build>();
    private static final Logger LOG = Logger.getLogger(Feed.class);

    public void addBuild(Build build) {
        this.items.add(build);
        Collections.sort(items, new BuildComparator(new AscendingDateComparator()));
    }

    public boolean isCurrentlyBroken() {
        Map<String, Boolean> history = new HashMap<String, Boolean>();
        for (Build build : items) {
            boolean broken = build.isBroken();
            String project = build.getProject();
            LOG.trace("BUILD [project:" + project + ", date:" + build.getDate() + "]:" + (broken ? "BROKEN" : "OK"));
            history.put(project, Boolean.valueOf(broken));
        }
        LOG.debug(history);
        return history.containsValue(Boolean.TRUE);
    }

    public int buildCount() {
        return items.size();
    }

    public List<Build> getBuilds() {
        return items;
    }

    private class BuildResult {
        private String name;
        private boolean broken;
        private Date when;

        public BuildResult(String name, Date when, boolean broken) {
            this.name = name;
            this.when = when;
            this.broken = broken;
        }

        public String getName() {
            return name;
        }

        public Date getWhen() {
            return when;
        }

        public boolean isBroken() {
            return broken;
        }
    }
}
